import axios from 'axios'
import { Notify, Dialog } from 'vant';
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
    baseURL: 'https://qa.fangzishen.com', // api 的 base_url
    // withCredentials: true, // 跨域请求时发送 cookiesstore
    timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        if (store.getters.token) {
            config.headers['Authorization'] = getToken()
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code !== 0) {
            Notify({
                message: res.msg,
                background: '#fa1919',
                duration: 3 * 1000
            })
            // 401:token失效;
            if (res.code === 401) {
                store.dispatch('user/resetToken').then(() => {
                    location.reload()
                })
            }
            if (res.code === 403) {
                Dialog.alert({
                    message: '你已被登出，请重新登录'
                }).then(() => {
                    // TODO add store
                    store.dispatch('user/resetToken').then(() => {
                        location.reload()
                    })
                });
            }
            return Promise.reject('error')
        } else {
            return res
        }
    },
    error => {
        Notify({
            message: error.message,
            background: '#fa1919',
            duration: 3 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
